package com.tim.wicket.examples;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.convert.IConverter;

import com.tim.wicket.examples.converter.CurrencyConverter;
import com.tim.wicket.examples.model.Cart;
import com.tim.wicket.examples.model.Cheese;

public class ShoppingCartPanel extends Panel {

	private final Cart cart;
	
	public ShoppingCartPanel(String id, Cart cart) {
		super(id);
		this.cart = cart;
		
		add(new ListView<Cheese>("cart", new PropertyModel<List<Cheese>>(this, "cart.cheeses")) {

			@Override
			protected void populateItem(ListItem<Cheese> item) {
				Cheese cheese = item.getModelObject();
				item.add(new Label("name", cheese.getName()));
				item.add(new Label("price", "$" + cheese.getPrice()));
				
				item.add(new Link<Cheese>("remove", item.getModel()) {
					@Override
					public void onClick() {
						Cheese cheese = getModelObject();
						getCart().getCheeses().remove(cheese);
					}
				});
			}
		});
		
		add(new Label("total", new PropertyModel<Double>(this, "cart.total")) {
			@Override
			public <C> IConverter<C> getConverter(Class<C> type) {
				return (IConverter<C>) new CurrencyConverter();
			}
		});

	}

	public Cart getCart() {
		return cart;
	}

}
